package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.pojo.dto.StatementInsertDTO;
import com.xbongbong.paas.pojo.vo.StatementAddVO;
import com.xbongbong.paas.script.distributor.StatementCreate;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.BasicConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * @Description
 * @author: shian
 * @date : 2021/1/18
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/script/statement")
public class AutoStatementScriptController {

    private static final Logger LOG = LoggerFactory.getLogger(AutoStatementScriptController.class);

    /**
     * 一天的时间
     */
    public static final Integer DAY_TIME = 86400;
    /**
     * 一周的时间
     */
    public static final Integer WEEK_TIME = 604800;

    @Resource
    private StatementCreate statementCreate;

    /**
     * 自动生成对账单
     * @param insertDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String createStatement(@RequestBody @Valid StatementInsertDTO insertDTO, BindingResult br) {
        XbbResponse<StatementAddVO> response;
        try {
            String key = insertDTO.getKey();
            if (!Objects.equals(key, BasicConstant.TASK_SECRET_KEY)) {
                LOG.error("对账单自动生成校验 密码错误，停止定时任务！");
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100066);
            }
            StatementAddVO addVO = statementCreate.autoCreate();
            response = new XbbResponse<>(addVO);
        } catch (XbbException e) {
            response = new XbbResponse<>(e);
        }
        return JSON.toJSONString(response);
    }
}
